#include "inc/FileIO.h"

#include "inc/qd_datas.h"
#include "inc/qd_types.h"
#include "inc/qd_utils.h"

FileIO::FileIO(const char *__filename, int blockSize, QUINT_64 size)
    : mBlockSize(blockSize), mSize(size)
{
    strcpy(mFilePath, __filename);
}

FileIO::FileIO(const char *_user, const char *_path, const char *_name, int blockSize, QUINT_64 size)
    : mBlockSize(blockSize), mSize(size)
{
    char filePath[256];

    splicString(filePath, sizeof(filePath), 5, QDENV::PATH, "/", _user, _path, _name);

    strcpy(mFilePath, filePath);
}

int FileIO::Open(const char * __mode){
    mFp = fopen(mFilePath, __mode);

    if(mFp == nullptr) {
        QD_LOGD("open %s faild!", mFilePath);
        return -1;
    }
    //QD_LOGD("open %s, %ld:%d", mFilePath, mSize, mBlockSize);

    return 0;
}
/*
int FileIO::Write(QINT_32 index, QINT_32 buffLen, QCHAR *buff){
    //QD_LOGD("%d %d %d", index, mBlockSize, buffLen);
    fseek(mFp, index * mBlockSize, SEEK_SET);
    int writeSize = fwrite(buff, 1, buffLen, mFp);
    //QD_LOGD("fwrite:%d", writeSize);
    int nf = fflush(mFp);
    //QD_LOGD("fflush file %d", nf);
    return nf;
}

int FileIO::Read(QINT_32 index, QCHAR *buff){
    fseek(mFp,index * mBlockSize, SEEK_SET);
    int rNum = fread(buff, 1, mBlockSize, mFp);
    //QD_LOGD("%d", rNum);
    return rNum;
}
*/
int FileIO::Write(char *buff, int len){

    int wSize = fwrite(buff, 1, len, mFp);
    int nf = fflush(mFp);
    return wSize;
}

int FileIO::Read(char *buff, int len){
    int rSize = fread(buff, 1, len, mFp);
    return rSize;
}

FILE *FileIO::getFP(){
    return mFp;
}
QUINT_64 FileIO::getSize(){

    return mSize;
}

void FileIO::Close(){
    int res = fclose(mFp);
    QD_LOGD("res:%d", res);
}

int FileIO::getBlockSize(){
    return mBlockSize;
}

FileIO::~FileIO(){
    fclose(mFp);
}

FileInfo::FileInfo(const char *_filePath){

    QCHAR  *mBasec = strdup(_filePath);  // 复制字符串, 需要销毁
    struct stat     fileStat;

    if (stat(_filePath, &fileStat) == 0) {
        QD_LOGD("read file info");

        mSize = fileStat.st_size;          // 文件大小

        realpath(mBasec, mFull);            // 绝对路径

        strcpy(mName, basename(mBasec));    // 文件名

        strcpy(mPath, dirname(mBasec));     // 上级路径 - 父路径

    } else {
        mSize = 0;
    }

    QD_LOGD("%s,%s,%s,%d", mFull, mPath, mName, mSize);

    free(mBasec);

}

char *FileInfo::getName(){

    return mName;

}

QUINT_64 FileInfo::getSize(){
    return mSize;
}

FileInfo::~FileInfo(){

}